package com.lcxw.hxzbadmin.controller.membercontroller;

import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lcxw.hxzbapi.entity.pojo.AddCoin;
import com.lcxw.hxzbapi.entity.response.Response;

@RestController
@CrossOrigin
@Slf4j
@RequestMapping("admin/user")
public class MemberCoinController {

    @Resource
    MemberCoinRealization memberCoinRealization;

    /**
     * 1、为用户加值接口
     * @param requestParams
     * @return
     */
    @PostMapping("/coin/add")
    public Response userCoinAdd(HttpServletRequest request, @RequestBody JSONObject requestParams){
        String adminName = requestParams.getString("adminName");
        String userName = requestParams.getString("userName");
        int coin = requestParams.getInteger("coin");
        log.info("admin {} add {} coin for user {}",adminName,coin,userName);
        //先操作给用户添加虚拟币
        try {
            memberCoinRealization.addCoin(userName,coin);
        } catch (Exception e) {
            return Response.dbFail(log,"admin add coin for user");
        }
        String ip = request.getRemoteAddr();
        //然后将加值记录存到数据库中
        try {
            memberCoinRealization.addCoinDetail(userName,coin,adminName,ip);
        } catch (Exception e) {
            return Response.dbFail(log,"add coin detail to db");
        }
        return Response.ok();

    }

    /**
     * 2、用户价值记录查询接口
     */
    @PostMapping("/coin/addDetail")
    public Response addCoinDetail(@RequestBody JSONObject requestParams){
        String userName = requestParams.getString("userName");
        String startTime = requestParams.getString("startTime");
        String endTime = requestParams.getString("endTime");
        String admin = requestParams.getString("admin");
        int pageIndex = requestParams.getInteger("pageIndex");
        int pageSize = requestParams.getInteger("pageSize");

        int sum = memberCoinRealization.getSumDetailsDync(userName,startTime,endTime,admin);
        List<AddCoin> addCoins = memberCoinRealization
            .getDetailDync(userName,startTime,endTime,admin,pageIndex,pageSize);

        Map<String,Object> data = new HashMap<>();
        data.put("sum",sum);
        data.put("addCoins",addCoins);
        return Response.ok(data);
    }


}
